/**
 *socket ，支持自动重连
 *
 * @class SDsocket
 */
class SDsocket {
    /**
     *连接的socket
     *
     * @private
     * @type {(WebSocket | undefined)}
     * @memberof SDsocket
     */
    private socket: WebSocket | undefined;
    /**
     *获取到数据的回调信息
     *
     * @private
     * @memberof SDsocket
     */
    private callBack: (data: any) => {};
    /**
     *连接的socket地址 ： 比如： 'ws://192.168.11.85:8000/ws'
     *
     * @private
     * @type {string}
     * @memberof SDsocket
     */
    private url: string;
    /**
     *连接错误的回调
     *
     * @private
     * @memberof SDsocket
     */
    private errorCallBack: (() => {}) | undefined;
    /**
     *连接成功的回调
     *
     * @private
     * @memberof SDsocket
     */
    private openCallBack: (() => {}) | undefined;
    constructor(url: string, callBack: () => {}, openCallBack?: () => {}, errorCallBack?: () => {}) {
        this.url = url;
        this.callBack = callBack;
        this.errorCallBack = errorCallBack;
        this.openCallBack = openCallBack;
        this.initSocket();
        window.onbeforeunload = () => {//监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
            this.socket && this.socket.close();
        }
    }

    /**
     *初始化创建socket
     *
     * @private
     * @memberof SDsocket
     */
    private initSocket() {
        this.socket = new WebSocket(this.url);
        // console.log('正在重新连接。。。')
        this.socket.onerror = () => {//socket 连接发生错误， 开始自动重连
            this.errorCallBack && this.errorCallBack();
                this.initSocket() ;
        }
        this.socket.onopen = () => {//socket连接通信成功的回调
            this.openCallBack && this.openCallBack();
        }
        this.socket.onmessage = (event) => {//socket连接成功
            try {
                this.callBack.call(this.socket, JSON.parse(event.data))
            } catch (e) {
                this.callBack.call(this, event.data.split("").reverse().join("").substring(1).replace(/\b(0+)/gi, ""));
            }
        }
    }
    /**
     *获取socket
     *
     * @returns
     * @memberof SDsocket
     */
    public getSocket() {
        return this.socket;
    }
}
export default SDsocket;